package com.club.controller;

import cn.dev33.satoken.stp.SaTokenInfo;
import cn.dev33.satoken.stp.StpUtil;
import com.club.common.R;
import com.club.entity.User;
import com.club.service.UserService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

/**
 * 认证控制器
 */
@RestController
@RequestMapping("/auth")
@Tag(name = "认证管理", description = "用户登录、注册等认证相关接口")
public class AuthController {

    @Autowired
    private UserService userService;

    /**
     * 用户登录
     */
    @PostMapping("/login")
    @Operation(summary = "用户登录", description = "用户登录接口")
    public R<SaTokenInfo> login(@RequestBody LoginRequest request) {
        // 用户登录验证
        User user = userService.login(request.getUsername(), request.getPassword());
        
        // 登录成功后，生成token
        StpUtil.login(user.getId());
        
        // 获取token信息
        SaTokenInfo tokenInfo = StpUtil.getTokenInfo();
        
        return R.ok(tokenInfo);
    }

    /**
     * 用户注册
     */
    @PostMapping("/register")
    @Operation(summary = "用户注册", description = "用户注册接口")
    public R<String> register(@RequestBody User user) {
        userService.register(user);
        return R.ok("注册成功");
    }

    /**
     * 用户登出
     */
    @PostMapping("/logout")
    @Operation(summary = "用户登出", description = "用户登出接口")
    public R<String> logout() {
        StpUtil.logout();
        return R.ok("登出成功");
    }

    /**
     * 获取当前用户信息
     */
    @GetMapping("/currentUser")
    @Operation(summary = "获取当前用户信息", description = "获取当前登录用户的信息")
    public R<User> getCurrentUser() {
        Long userId = StpUtil.getLoginIdAsLong();
        User user = userService.getById(userId);
        // 隐藏敏感信息
        user.setPassword(null);
        return R.ok(user);
    }

    /**
     * 登录请求参数
     */
    @lombok.Data
    public static class LoginRequest {
        private String username;
        private String password;
    }
}